package com.uduemc.biso.node.web.api.design.controller;

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.uduemc.biso.core.utils.HttpUtil;
import com.uduemc.biso.node.core.common.dto.FeignPageUtil;
import com.uduemc.biso.node.core.common.entities.SRBackendHtml;
import com.uduemc.biso.node.core.common.entities.SiteBasic;
import com.uduemc.biso.node.core.common.entities.SitePage;
import com.uduemc.biso.node.core.common.utils.PageUtil;
import com.uduemc.biso.node.core.common.utils.SRHtmlUtil;
import com.uduemc.biso.node.web.api.component.SiteHolder;
import com.uduemc.biso.node.web.api.config.SpringContextUtil;
import com.uduemc.biso.node.web.api.design.service.DPageService;
import com.uduemc.biso.node.web.api.design.service.DSiteService;
import com.uduemc.biso.node.web.api.exception.NotFoundDesignPageException;
import com.uduemc.biso.node.web.api.exception.NotFoundException;
import com.uduemc.biso.node.web.api.exception.NotFoundSitePageException;
import com.uduemc.biso.node.web.api.service.SystemTypeService;

@Controller
@RequestMapping("/api/design")
public class DIndexController {

	private static final Logger logger = LoggerFactory.getLogger(DIndexController.class);

	@Autowired
	private SiteHolder siteHolder;

	@Autowired
	private DSiteService dSiteServiceImpl;

	@Autowired
	private SystemTypeService systemTypeServiceImpl;

	@Autowired
	private DPageService dPageServiceImpl;

	@Autowired
	private SpringContextUtil springContextUtil;

	@GetMapping("/*/*/backend.*.hot-update.js.map")
	public void indexbackend(HttpServletRequest request, HttpServletResponse response) throws IOException {
		// 通过 获取欢迎页的基础信息
		if (springContextUtil.local()) {
			response.setContentType("application/json;charset=UTF-8");
			response.setHeader("Pragma", "No-cache");
			response.setHeader("Cache-Control", "no-cache");
			response.setDateHeader("Expires", 0);
			String requestURI = request.getRequestURI();
			String string = HttpUtil.get("http://localhost:2399" + requestURI.substring(requestURI.lastIndexOf("/")));
			response.getWriter().write(string);
			response.getWriter().flush();
		}
	}

	/**
	 * 进入此 handler 表示，肯定是一个需要展示的页面
	 * 
	 * @throws NotFoundException
	 * @throws IOException
	 * @throws JsonProcessingException
	 * @throws JsonMappingException
	 * @throws JsonParseException
	 * @throws NotFoundDesignPageException
	 * @throws NotFoundSitePageException
	 */
	@GetMapping(value = { "/*/*/**" })
	@ResponseBody
	public String index() throws NotFoundException, JsonParseException, JsonMappingException, JsonProcessingException,
			IOException, NotFoundSitePageException, NotFoundDesignPageException {
		// 获取 SitePage 暂存如 ThreadLocal 中
		SitePage sitePage = getSitePage();
		siteHolder.add(sitePage);
		// 初始化并添加SRHtml入 siteHolder 中
		SRBackendHtml srBackendHtml = new SRBackendHtml();
		siteHolder.add(srBackendHtml);

		// 拼凑 SRHtml 页面的内容
		boolean bool = dSiteServiceImpl.getSRHtml();
		if (!bool) {
			throw new NotFoundException("无法正确运行 dSiteServiceImpl.getSRHtml();");
		}

		// 组装 HTML 内容并返回
		return SRHtmlUtil.getHtml(siteHolder.getSRBackendHtml());
	}

	protected SitePage getSitePage() throws NotFoundException, JsonParseException, JsonMappingException,
			JsonProcessingException, IOException, NotFoundSitePageException, NotFoundDesignPageException {
		// 首先获取 请求方的最基本的 SiteBasic 数据
		SiteBasic siteBasic = siteHolder.getSiteBasic();

		// 通过页面工具 PageUtil 进行匹配
		PageUtil pageUtil = new PageUtil(siteBasic.getSiteUri());
		if (!pageUtil.matchPage()) {
			// 给予一个404页面
			throw new NotFoundException("无法识别页面！ siteUri: " + siteBasic.getSiteUri());
		}

		// 通过 PageUtil 获取当前页面的 FeignPageUtil 数据
		FeignPageUtil feignPageUtil = pageUtil.getFeignPageUtil(siteHolder.getHost().getId(),
				siteHolder.getSite().getId());

		// 通过服务请求获取 SitePage 数据
		SitePage sitePage = null;
		try {
			sitePage = dSiteServiceImpl.getSitePageByFeignPageUtil(feignPageUtil);
		} catch (IOException e) {
			e.printStackTrace();
		}
		if (sitePage == null) {
			logger.info("feignPageUtil 提交的数据异常！feignPageUtil: " + feignPageUtil);
			boolean bool = dPageServiceImpl.existsCurrentDeignPage();
			if (bool) {
				// 否则抛出未能通过后缀获取页面信息的页面内容
				throw new NotFoundSitePageException("未能通过 feignPageUtil 获取到页面数据 feignPageUtil: " + feignPageUtil,
						feignPageUtil);
			} else {
				// 这里判断是否拥有页面数据，如果没有则直接抛出 NotFoundDesignPageException 异常，要求前台显示增加页面
				throw new NotFoundDesignPageException("未能通过 feignPageUtil 获取到页面数据 feignPageUtil: " + feignPageUtil);
			}
		}

		// 甄别页面
		boolean bool = pageUtil.screenSystemPage(sitePage, systemTypeServiceImpl.getInfos());
		if (!bool) {
			logger.error("甄别系统页面出错！ pageUtil: " + pageUtil);
			throw new NotFoundException("甄别系统页面出错！ pageUtil: " + pageUtil);
		}

		logger.info("请求页面的数据转化 sitePage: " + sitePage.toString());

		return sitePage;
	}
}
